package com.tange.ai.iot.client.gnssa

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import base.http.utils.RetrofitBuilder
import com.alibaba.sdk.android.push.CloudPushService
import com.alibaba.sdk.android.push.CommonCallback
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory
import com.clj.fastble.BleManager
import com.tange.ai.iot.client.gnssa.home.HomeActivity
import com.tange.ai.iot.client.gnssa.token.XqAccountLoginActivity
import com.tange.ai.iot.client.gnssa.token.InternalAccountLoginActivity
import com.tange.ai.iot.client.gnssa.utils.SP
import com.tange.base.toolkit.PreferenceUtil
import com.tange.base.toolkit.ui
import com.tange.core.access.token.Authentication
import com.tange.core.backend.service.ep.Env
import com.tange.core.backend.service.interceptor.HttpLoggingInterceptor
import com.tange.core.camera.base.tookit.PeerServerLogging
import com.tange.core.initialization.Configurations
import com.tange.core.initialization.TGCore
import com.tange.core.message.distribution.Message
import com.tange.core.message.distribution.PersistentConnectionMessage
import com.tange.module.core.wifi.scan.AccessPointScanImpl
import com.tange.module.core.wifi.scan.WiFiScanManager
import com.tange.module.qrcode.scan.QrCodeBitmap
import com.tange.module.qrcode.scan.QrCodeBitmapImpl
import com.tange.module.qrcode.scan.QrCodeRecognitionFactoryImpl
import com.tange.module.qrcode.scan.QrCodeRecognitionHub
import com.tencent.bugly.library.Bugly
import com.tencent.bugly.library.BuglyAppVersionMode
import com.tencent.bugly.library.BuglyBuilder
import com.tencent.bugly.library.BuglyLogLevel
import com.tg.appcommon.android.TGLog
import org.json.JSONObject


class App : Application() {

    companion object {
        const val TAG = "App_"
        const val compressLevel=1
        fun getToken(): String {
            return "";
        }
    }



    private val activities = ArrayList<Activity>()

    override fun onCreate() {
        super.onCreate()

        SP.saveString(this,Constants.KEY_CUSTOM_APP_ID,"AD_2qzHBNfFI4AjfafBTi4HZaBqJtL")
        SP.saveString(this,Constants.KEY_CUSTOM_APP_PKG,"com.gnssa.app")

        val customAppId = SP.getString(this, Constants.KEY_CUSTOM_APP_ID, "").trim()
        val customPkgName = SP.getString(this, Constants.KEY_CUSTOM_APP_PKG, "").trim()
        val customEnv = SP.getString(this, Constants.KEY_CUSTOM_APP_ENV, "").trim()

        val _appId = if (!TextUtils.isEmpty(customAppId)) customAppId else BuildConfig.TG_APP_ID
        val _pkgName = if (!TextUtils.isEmpty(customPkgName)) customPkgName else packageName
        val _env = when (customEnv) {
            "0" -> Env.PRODUCT
            "1" -> Env.PRE_PRODUCT
            "2" -> Env.TEST
            else -> Env.PRODUCT
        }


        val configurations = Configurations.Builder(this)
            .setAppId(_appId) // 如需修改APP_ID，点击“首页”-“右下角”-“应用配置”按钮即可
            .setPackageName(_pkgName) // 如需修改包名，点击“首页”-“右下角”-“应用配置”按钮即可
            .setEnvironment(_env) // 如需修改平台服务端运行环境，点击“首页”-“右下角”-“应用配置”按钮即可
            .enableDebugMode(BuildConfig.DEBUG) //你应当 仅在 Debug包 时，才启用调试模式，避免信息泄漏以及性能问题！
            .build()

        TGCore.initialize(configurations)
        // 设置AP扫描具体实现
        WiFiScanManager.setWiFiScan(AccessPointScanImpl())
        // 设置二维码扫描与识别能力的具体实现
        QrCodeRecognitionHub.register(QrCodeRecognitionFactoryImpl())
        QrCodeBitmap.setQrCodeBitmapImpl(QrCodeBitmapImpl())
        //VideoCapabilityCore.registerVideoCapability( CropVideoCapability() )
        PersistentConnectionMessage.observe {
            if (it.name?.contains("doorbell") == true) {
                processRingEvent(it)
            } else {
                Toast.makeText(this, "收到长连接消息：\n$it", Toast.LENGTH_LONG).show()
            }
        }

        // 全局监听用户令牌失效的状态 并进行相应处理，此处示例为返回根Activity.
        observeOnVerificationFailed()

        RetrofitBuilder.getInstance().setBaseUrl(BASE_URL)

        // 初始化第三方推送SDK
        initPushing(this)

        initBugly(this)
        // 你的APP 不应 调这一行
        HttpLoggingInterceptor.enableCache = true
        PeerServerLogging.ENABLE = true

        BleManager.getInstance().init(this)
    }
    fun initBugly(context: Context?) {
//        // 1. 初始化参数预构建，必需设置初始化参数
//        val appID = "d4149a5c8f" // 【必需设置】在Bugly 专业版 注册产品的appID
//        val appKey = "0a20e8fc-464e-44f4-a64b-0ffb53df3a3e" // 【必需设置】在Bugly 专业版 注册产品的appKey
//        val builder = BuglyBuilder(appID, appKey)
//
//        builder.appVersionType = BuglyAppVersionMode.DEBUG // 【推荐设置】设置版本类型
//
//        // 3. 更多初始化参数，按需设置初始化参数
//        builder.appChannel = "appChannel" // 设置App的渠道
//        builder.logLevel = BuglyLogLevel.LEVEL_DEBUG // 设置日志打印级别，级别可从BuglyLogLevel中获取
//        builder.enableAllThreadStackCrash = true // 设置Crash时是否抓取全部线程堆栈，默认开启
//        builder.enableAllThreadStackAnr = true // 设置Anr时是否抓取全部线程堆栈，默认开启
//        builder.enableCrashProtect = true // 设置性能监控时开启Crash保护模式，默认开启
//        builder.debugMode = false // 设置debug模式，可在调试阶段开启
//
//        // 4. 设置回调方法，按需设置初始化参数
//        builder.setCrashHandleListener(null) // 设置Crash处理回调接口，详情见回调接口
//        builder.setUploadHandleListener(null) // 设置Crash上报回调接口，详情见回调接口
//
//        // 5. 初始化，必需调用
//        Bugly.init(context, builder)
    }
    private fun processRingEvent(it: Message) {
        ui {
            it.param?.let {
                try {
                    val jsonObject = JSONObject(it)
                    val deviceId = jsonObject.getString("uuid")
                    val image = jsonObject.getString("image_path")
                    LocalBroadcastManager.getInstance(this@App.applicationContext).sendBroadcast(Intent(
                        HomeActivity.INTENT_ACTION_RING).apply {
                        putExtra(HomeActivity.PARAM_DEVICE_ID, deviceId)
                    })
                } catch (e: Throwable) {
                    Toast.makeText(this, "收到长连接消息：\n$it", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    /**
     * 初始化第三方推送SDK
     * @param applicationContext
     */
    private fun initPushing(applicationContext: Context) {
        TGLog.i(TAG, "[initPushing] ...")
        PushServiceFactory.init(applicationContext)
        val pushService = PushServiceFactory.getCloudPushService()
        if (BuildConfig.DEBUG )pushService.setLogLevel(CloudPushService.LOG_DEBUG)
        pushService.register(applicationContext, object : CommonCallback {
            override fun onSuccess(response: String?) {
                val deviceId = pushService.deviceId
                TGLog.i(TAG, "[initPushing][onSuccess] $deviceId")
            }

            override fun onFailed(errorCode: String, errorMessage: String) {
                TGLog.i(TAG, "[initPushing][onFailed] $errorCode $errorMessage")
            }
        })
    }

    private fun observeOnVerificationFailed() {

        Authentication.observeOnVerificationFailed {

            ui {
                Toast.makeText(this, "用户令牌过期或者被挤下线！\n你需要重新登录", Toast.LENGTH_LONG).show()
                activities.forEach { it.finish() }
//                Intent(this@App, DispatchActivity::class.java).also {
//                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                    startActivity(it)
//                }

                PreferenceUtil.setString(
                    applicationContext,
                    InternalAccountLoginActivity.PRE_TOKEN,
                    ""
                )

                Intent(this@App, XqAccountLoginActivity::class.java).also {
                    it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(it)
                }
            }
        }

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(p0: Activity, p1: Bundle?) { activities.add(p0) }
            override fun onActivityStarted(p0: Activity) {}
            override fun onActivityResumed(p0: Activity) {}
            override fun onActivityPaused(p0: Activity) {}
            override fun onActivityStopped(p0: Activity) {}
            override fun onActivitySaveInstanceState(p0: Activity, p1: Bundle) {}
            override fun onActivityDestroyed(p0: Activity) { activities.remove(p0) }
        })
    }


}